package com.sdp.irrigation.kafka.biz.impl;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import com.alibaba.fastjson.JSONObject;
import com.sdp.irrigation.cache.EqRealTimeCache;
import com.sdp.irrigation.cache.EqValveCache;
import com.sdp.irrigation.db.irrigation_eq_log_eq_status.service.IIrrigationEqLogEqStatusService;
import com.sdp.irrigation.db.irrigation_eq_real_time.service.IIrrigationEqRealTimeService;
import com.sdp.irrigation.db.irrigation_eq_valve.service.IIrrigationEqValveService;
import com.sdp.irrigation.entity.IrrigationEqLogEqStatus;
import com.sdp.irrigation.entity.IrrigationEqRealTime;
import com.sdp.irrigation.entity.IrrigationEqValve;
import com.sdp.irrigation.kafka.biz.IProtocolBiz;
import com.sdp.irrigation.protocol.CommPackage;
import com.sdp.irrigation.utils.BeanUtils;
import com.sdp.irrigation.utils.CommConstants;
import com.sdp.irrigation.utils.IrrigationConstants;
import com.sdp.irrigation.utils.JsonUtils;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class ReportBiz implements IProtocolBiz {

	@Autowired
	private EqRealTimeCache eqRealTimeCache;
	
	@Autowired
	private EqValveCache eqValveCache;
	
	@Autowired
	private IIrrigationEqLogEqStatusService eqLogEqStatusService;
	
	@Autowired
	private IIrrigationEqValveService eqValveService;
	
	@Autowired 
	private IIrrigationEqRealTimeService eqRealTimeService;
	
	private void copyFieldValue(IrrigationEqLogEqStatus eqLogEqStatus, CommPackage commPackage) {
		JSONObject body = commPackage.getBody();
		if (body != null && body.containsKey("devStatus")) {
			eqLogEqStatus.setDevStatus(body.getString("devStatus"));
		}
		if (body != null && body.containsKey("sumWater")) {
			eqLogEqStatus.setSumWater(new BigDecimal(body.getString("sumWater")));
		}
		if (body != null && body.containsKey("sumEle")) {
			eqLogEqStatus.setSumEle(new BigDecimal(body.getString("sumEle")));
		}
		if (body != null && body.containsKey("batVol")) {
			eqLogEqStatus.setBatVol(new BigDecimal(body.getString("batVol")));
		}
		if (body != null && body.containsKey("gprsRssi")) {
			eqLogEqStatus.setGprsRssi(body.getString("gprsRssi"));
		}
		if (body != null && body.containsKey("Ua")) {
			eqLogEqStatus.setUa(new BigDecimal(body.getString("Ua")));
		}
		if (body != null && body.containsKey("Ub")) {
			eqLogEqStatus.setUb(new BigDecimal(body.getString("Ub")));
		}
		if (body != null && body.containsKey("Uc")) {
			eqLogEqStatus.setUc(new BigDecimal(body.getString("Uc")));
		}
		if (body != null && body.containsKey("Ia")) {
			eqLogEqStatus.setIa(new BigDecimal(body.getString("Ia")));
		}
		if (body != null && body.containsKey("Ib")) {
			eqLogEqStatus.setIb(new BigDecimal(body.getString("Ib")));
		}
		if (body != null && body.containsKey("Ic")) {
			eqLogEqStatus.setIc(new BigDecimal(body.getString("Ic")));
		}
		if (body != null && body.containsKey("Pt")) {
			eqLogEqStatus.setPt(new BigDecimal(body.getString("Pt")));
		}
		
		
	}
	
	public String getEqValveMapKey(String eqNo, String valveNo) {
		StringBuffer sbf = new StringBuffer();
		sbf.append(eqNo).append("#").append(valveNo);
		return sbf.toString();
	}
	
	
	private void updateEqStatus(IrrigationEqRealTime eqRealTime, IrrigationEqRealTime eqRealTimeUpdate, IrrigationEqLogEqStatus eqLogEqStatus, Map<String,IrrigationEqValve> eqValveMap, Map<String,IrrigationEqValve> eqValveTempMap) {
		//设备上报的时间不准，优先使用服务器的更新时间
		eqRealTimeUpdate.setUpdateTime(eqLogEqStatus.getUpdateTime());
//		eqRealTimeUpdate.setUpdateTime(eqLogEqStatus.getUploadTime());
		eqRealTimeUpdate.setOnlineStatus(IrrigationConstants.设备在线状态_在线.getCode());
		eqRealTime.setUpdateTime(eqRealTimeUpdate.getUpdateTime());
		eqRealTime.setOnlineStatus(eqRealTimeUpdate.getOnlineStatus());
		if (!StringUtils.isEmpty(eqLogEqStatus.getDevStatus())) {
			String reversedStatus = new StringBuilder(eqLogEqStatus.getDevStatus()).reverse().toString();
			// 3-灌溉泵状态
			eqRealTimeUpdate.setIrrigationStatus(getStatus(reversedStatus, 3));
			eqRealTime.setIrrigationStatus(eqRealTimeUpdate.getIrrigationStatus());
			// 1-搅拌泵状态
			eqRealTimeUpdate.setStirringStatus(getStatus(reversedStatus, 1));
			eqRealTime.setStirringStatus(eqRealTimeUpdate.getStirringStatus());
			// 2-施肥泵状态
			eqRealTimeUpdate.setFertilizationStatus(getStatus(reversedStatus, 2));
			eqRealTime.setFertilizationStatus(eqRealTimeUpdate.getFertilizationStatus());
			// 4-加水状态
			eqRealTimeUpdate.setWateringStatus(getStatus(reversedStatus, 4));
			eqRealTime.setWateringStatus(eqRealTimeUpdate.getWateringStatus());
			// 5-排沙状态
		    eqRealTimeUpdate.setDesiltingStatus(getStatus(reversedStatus, 5));
		    eqRealTime.setDesiltingStatus(eqRealTimeUpdate.getDesiltingStatus());
		    // 0-是否工作中
		    eqRealTimeUpdate.setWorkStatus(getStatus(reversedStatus, 0));
		    eqRealTime.setWorkStatus(eqRealTimeUpdate.getWorkStatus());

			for (Entry<String,IrrigationEqValve> entry : eqValveTempMap.entrySet()) {
				IrrigationEqValve eqValve = entry.getValue();
				eqValve.setUpdateTime(LocalDateTime.now());
				//获取阀门状态
				eqValve.setSwitchStatus(getStatus(reversedStatus, 5 + eqValve.getSerialNo()));
				String valveMapKey = getEqValveMapKey(eqRealTime.getEqNo(), entry.getKey());
				if (!eqValveMap.containsKey(valveMapKey)) {
					eqValveMap.put(valveMapKey, eqValve);
				}
			}
			
		}
	}
	
	private static String getStatus(String status, int position) {
		//IrrigationConstants
		if (position < status.length()) {
			return Character.toString(status.charAt(position)); 
		}
		else {
			log.error("索引值： {}的值超出devStatus字符串长度： {}", position, status.length());
//			throw new RuntimeException("索引position的值超出devStatus字符串长度");
		}
		return IrrigationConstants.否.getCode();
	}
	

	@Override
	public void execute(List<CommPackage> packageList) {
		if (packageList.size() > 0) {
			List<IrrigationEqLogEqStatus> insertList = new ArrayList<>();
			Map<String, IrrigationEqRealTime> eqRealTimeMap = new HashMap<>();
			Map<String, IrrigationEqValve> eqValveMap = new HashMap<>();
			
			for (CommPackage commPackage : packageList) {
				String devSn = CommConstants.getReportCommPackageDevSn(commPackage);
				if (!StringUtils.isEmpty(devSn)) {
					IrrigationEqLogEqStatus eqLogEqStatus = new IrrigationEqLogEqStatus();
					eqLogEqStatus.setEqNo(devSn);
					copyFieldValue(eqLogEqStatus, commPackage);
					eqLogEqStatus.setCreateTime(LocalDateTime.now());
					eqLogEqStatus.setUpdateTime(LocalDateTime.now());
					//上报时间的处理
					if (!StringUtils.isEmpty(commPackage.getPakSn())) {
						eqLogEqStatus.setUploadTime(CommConstants.pakSn2LocalDateTime(commPackage.getPakSn()));
					}
					eqLogEqStatus.setProtocolContent(JsonUtils.toJSONString(commPackage));
					insertList.add(eqLogEqStatus);
					
					//处理缓存
					IrrigationEqRealTime eqRealTime = eqRealTimeCache.getEqRealTimeCache(devSn);
					Map<String, IrrigationEqValve> eqValveTempMap = eqValveCache.getEqValveRealTimeCache(devSn);
					
					if (eqRealTime != null && !StringUtils.isEmpty(eqRealTime.getEqNo())) {
						//更新缓存的信息
						
						//新建对象，对缓存进行部分更新
						IrrigationEqRealTime eqRealTimeUpdate = new IrrigationEqRealTime();
						updateEqStatus(eqRealTime, eqRealTimeUpdate, eqLogEqStatus, eqValveMap, eqValveTempMap);
						eqRealTimeCache.updateEqRealTimeCache(devSn, BeanUtils.redisBean2Map(eqRealTimeUpdate));
						eqValveCache.updateEqValveCache(devSn, eqValveTempMap);
						
						//更新数据库信息
						if (!eqRealTimeMap.containsKey(devSn)) {
							eqRealTimeMap.put(devSn, eqRealTime);
						}
					}
				}
			}
			
			if (eqRealTimeMap.size() > 0) {
				eqRealTimeService.updateBatchById(new ArrayList<>(eqRealTimeMap.values()));
			}
			
			if (eqValveMap.size() > 0) {
				eqValveService.updateBatchById(new ArrayList<>(eqValveMap.values()));
			}
			
			if (insertList.size() > 0) {
				eqLogEqStatusService.saveBatch(insertList);
			}
		}
		
	}
	
	
	
	
	
	
}
